import {
  MOCK_DATA,
  BASE_HEIGHT,
  HEIGHT_RATIO,
  PADDING_RATIO,
  MODULE_INCREASE_COEFFICIENT,
  DELAY_TIME,
  STARTING_VALUE_COMPONENT,
  DEFAULT_COORDINATE,
  MODULE_TYPE,
} from "@/utils/mockConfiguration/mockConfig.js";
import { nextTick } from "vue";
import { debounce } from "lodash";
const { SCALED_FIXED_SCALE_MODULE } = MODULE_TYPE;
export const useTemplateEditing = defineStore("templateEditing", {
  state: () => ({
    currentUserInfo: {}, //当前用户信息
    currentSettings: MOCK_DATA, //当前全部默认设置
    templatePageIndex: null, //当前模板模块索引
    selectedModules: [], //选中模块
    menuButton: "basicConfiguration", //菜单按钮
    templateSettings: MOCK_DATA.baseConfig, //当前模板配置
    fileName: "", //初始化临时文件名称
    groupName: null, //组名
    renderKey: STARTING_VALUE_COMPONENT, //刷新组件
    baseHeight: BASE_HEIGHT, //默认高度
    renderedIds: [], //渲染组件id
    votingData: [], //投票数据
    buttonYCoordinates: DEFAULT_COORDINATE, //按钮Y坐标
    disabledQuestionRules: [], //禁答题规则
    requiredQuestionRules: [], //必答题规则
    optionalQuestionRules: [], //选答题规则
    submitButton: false, //提交按钮状态
  }),

  actions: {
    /**
     * 模板模块选择
     * @param {Object} item 当前模块
     * @param {String} index 索引
     */
    templateSelection(item, index) {
      const templateSelection = {
        menuButton: item.moduleId, //配置切换
        templatePageIndex: index, //当前模板模块索引
        templateSettings: item, //当前模板配置
        fileName: "", //初始化临时文件名称
      };
      Object.assign(this, templateSelection);
    },

    /**
     * 模块自适应
     * @param {String} id 模块id
     */
    autoHeight: debounce(function (id) {
      const { modules } = this.currentSettings;
      // 判断是否已经渲染过
      if (this.renderedIds.includes(id)) {
        return;
      }
      this.renderedIds.push(id);
      nextTick(() => {
        const moduleNodes = document.querySelectorAll(".body-item"); //所有模块节点
        const cssStyleData = modules.map(item => item.cssStyle); //获取所有模块样式
        moduleNodes.forEach(item => {
          const {
            dataset: { index, moduleid },
            offsetWidth,
          } = item;
          const childNodes = item.querySelector(".item-content"); //获取当前内容节点
          const cssStyle = cssStyleData.find(value => value.i === index); //需要获取当前模块样式
          const { aspectRatio, paddingPercent } = cssStyle;
          const height = SCALED_FIXED_SCALE_MODULE.includes(moduleid)
            ? offsetWidth * aspectRatio
            : childNodes.offsetHeight + (offsetWidth * paddingPercent) / PADDING_RATIO;
          cssStyle.h = Math.ceil(height / HEIGHT_RATIO);
        });
      });
      this.renderKey += MODULE_INCREASE_COEFFICIENT;

      //自适应完成之后计算最后一个模块的坐标
      requestAnimationFrame(() => {
        const newData = modules.map(item => toRaw(item.cssStyle));
        if (!newData.length) {
          this.buttonYCoordinates = DEFAULT_COORDINATE;
          return;
        }
        const { y, h } = newData.reduce((maxModule, currentModule) =>
          currentModule.y > maxModule.y ? currentModule : maxModule,
        );
        this.buttonYCoordinates = y + h;
      });
    }, DELAY_TIME),

    // 更新窗口尺寸
    updateDimensions(id) {
      this.autoHeight(id);
    },
  },

  getters: {
    /**
     * 获取模板页面
     */
    templatePage(state) {
      return state.currentSettings.modules;
    },
  },
});
